package com.sam.core.util;

import java.lang.reflect.Modifier;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

/**
 * @project mould
 * @author Sam
 * @version
 * @date Dec 1, 2009 5:12:35 PM
 */
public class BeanUtils {
	private static Logger log = LoggerFactory.getLogger("eman");

	public static void copyProperties(Object dest, Object orig) {
		try {
			org.apache.commons.beanutils.BeanUtils.copyProperties(dest, orig);
		} catch (Exception e) {
			log.error("copy properties faild", e);
		}
	}

	public static Object getProperties(String propName, Object bean) {
		java.lang.reflect.Field field = getDeclaredField(bean, propName);

		if (field == null)
			throw new IllegalArgumentException("Could not find field [" + propName
					+ "] on target [" + bean + "]");

		makeAccessible(field);

		Object result = null;
		try {
			result = field.get(bean);
		} catch (IllegalAccessException e) {
			log.error("不可能抛出的异常{}", e.getMessage());
		}
		return result;
	}

	protected static void makeAccessible(final java.lang.reflect.Field field) {
		if (!Modifier.isPublic(field.getModifiers())
				|| !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
			field.setAccessible(true);
		}
	}

	protected static java.lang.reflect.Field getDeclaredField(final Object object,
			final String fieldName) {
		Assert.notNull(object, "object不能为空");
		Assert.hasText(fieldName, "fieldName");
		for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass
				.getSuperclass()) {
			try {
				return superClass.getDeclaredField(fieldName);
			} catch (NoSuchFieldException e) {
				// Field不在当前类定义,继续向上转型
			}
		}
		return null;
	}
}
